import 'dart:io';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';
import 'package:live_music/components/common/videoPage.dart';
import 'package:live_music/components/ui/tag.dart';
import 'package:live_music/components/ui/theme.dart';
import 'package:live_music/event/momonEvent.dart';
import 'package:live_music/http/http_utils.dart';
import 'package:live_music/models/moment_detail_model.dart';
import 'package:live_music/models/tag_model.dart';
import 'package:live_music/pages/friendList/index.dart';
import 'package:live_music/pages/publish/widget/frinend_list_select_publish.dart';
import 'package:live_music/pages/publish/widget/tag_list.dart';
import 'package:live_music/pages/publish/widget/topic_list.dart';
import 'package:live_music/pages/publish/widget/topic_list_select_publish.dart';
import 'package:live_music/services/publishService.dart';
import 'package:live_music/utils/cgq_utils.dart';
import 'package:live_music/utils/colors.dart';
import 'package:live_music/utils/common.dart';
import 'package:live_music/utils/eventBusUtils.dart';
import 'package:live_music/utils/oss.dart';
import 'package:live_music/utils/toast_utils.dart';
import 'package:live_music/utils/util.dart';
import 'package:path_provider/path_provider.dart';
import 'package:video_player/video_player.dart';

///发布页面
class FeedDouYinPublishPage extends StatefulWidget {
  final String publishType;
  final PublishFileMgs publishFileMgs;
  final Map<String, dynamic> videoCoverInfo;
  final String contentText;
  final String videoText;
  final String videoSourceUrl;
  FeedDouYinPublishPage(
      {Key key,
      this.publishType,
      this.publishFileMgs,
      this.videoCoverInfo,
      this.contentText,
      this.videoText,
      this.videoSourceUrl})
      : super(key: key);

  @override
  _FeedDouYinPublishPageState createState() {
    return _FeedDouYinPublishPageState();
  }
}

class _FeedDouYinPublishPageState extends State<FeedDouYinPublishPage> {
  String videoFilePath;
  File videoFile;
  String ossFileURL = "";
  double filePercentage = 0;
  List<dynamic> _imageFileList = [];
  Map<String, dynamic> videoCoverInfo = {
    "coverHeight": "",
    "coverUrl": "",
    "coverWidth": "",
  };
  String coverPath;
  TextEditingController _editingContentController = TextEditingController();
  TextEditingController _editingFileController = TextEditingController();
  VideoPlayerController videoPlayerController;
  String momentType;
  //图片  选择和上传
  final ImagePicker _picker = ImagePicker();
  FocusNode _focusNode = FocusNode();
  String momentContent = "";
  List<TagModel> tabModelList = [];
  bool disabledPublish = true;
  @override
  void initState() {
    super.initState();

    // videoCoverInfo = widget.videoCoverInfo;
    _editingContentController.text = widget.contentText;
    if (widget.contentText != null) {
      setState(() {
        momentContent = widget.contentText;
        _editingContentController.text = widget.contentText;
      });
    }
    if (widget.videoText != null) {
      _editingFileController.text = widget.videoText;
    }

    setState(() {
      momentType = widget.publishType;
    });
    if (widget.publishType == PublishType.video ||
        widget.publishType == PublishType.file) {
      _uploadFile(widget.publishFileMgs.path);
    }
    if (widget.publishType == PublishType.video) {
      initVideoPlayerController();
    }

    EventBusUtils.getInstance().on<SelectFriendPublishEvent>().listen((event) {
      setState(() {
        _editingContentController.text =
            _editingContentController.text + event.name + " ";
      });
    });
    EventBusUtils.getInstance().on<AddTagEvent>().listen((event) {
      setState(() {
        //  TagModel
        tabModelList.add(event.tabItem);
      });
    });
    EventBusUtils.getInstance().on<SelectTopicPublishEvent>().listen((event) {
      setState(() {
        _editingContentController.text =
            _editingContentController.text + event.name + " ";
      });
    });
  }

  initVideoPlayerController() async {
    videoPlayerController =
        VideoPlayerController.file(File(widget.publishFileMgs.path));
    await videoPlayerController.initialize();
  }

  _uploadFile(path) async {
    ossFileURL = await UploadOss.upload(File(path),
        rootDir: widget.publishType == PublishType.video
            ? "moment/video"
            : "moment/file",
        onSendProgress: (percentage) => {
              print(filePercentage),
              setState(() {
                filePercentage = percentage;
              })
            });
 if (widget.publishType == PublishType.video) {
            Directory storageDir = await getApplicationDocumentsDirectory();
      String storagePath = storageDir.path;
      String savePath = storagePath + "/" + getRandom(12) + ".jpg";
      File file = new File(savePath);
       var response = await HttpUtils.downImage(url: ossFileURL+ "?x-oss-process=video/snapshot,t_0,f_jpg,w_0,h_0,m_fast,ar_auto");
       await file.writeAsBytes(response.data, mode: FileMode.append);
     videoCoverInfo['coverUrl']=   await UploadOss.upload(file, rootDir: "moment/image");
     videoCoverInfo[ "coverHeight"]= videoPlayerController.value.size.height;
         videoCoverInfo[ "coverWidth"]=  videoPlayerController.value.size.width;
   setState(() {
      ossFileURL =ossFileURL;
        videoCoverInfo =videoCoverInfo;
    });
 }
    
    if (ossFileURL == '') {
      if (widget.publishType == PublishType.video) {
        ToastUtils.showToast("视频上传失败!");
        Get.back();
      } else {
        ToastUtils.showToast("文件上传失败!");
        Get.back();
      }
    }
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ColorRes.themeBg,
      appBar: _getAppBar(),
      body: SingleChildScrollView(child: _getBody(context)),
    );
  }

  AppBar _getAppBar() {
    return AppBar(
      backgroundColor: Colors.white,
      actions: [
        Container(
            margin: EdgeInsets.symmetric(horizontal: 16, vertical: 15),
            width: 60,
            alignment: Alignment.center,
            child: ElevatedButton(
                style: ButtonStyle(
                    shape: MaterialStateProperty.all(RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(20))),
                    backgroundColor: MaterialStateProperty.all(
                      Colors.redAccent,
                    )),
                onPressed: disabledPublish ? _publish : null,
                child: const Center(
                  child: Text(
                    '发布',
                    style: TextStyle(
                        color: Colors.white,
                        fontSize: 12,
                        fontWeight: FontWeight.w500),
                  ),
                ))),
      ],
      title: Text(
        '发布',
        style: TextStyle(color: Colors.black, fontSize: 16),
      ),
      centerTitle: true,
    );
  }

  _getBody(BuildContext context) {
    return Container(
      constraints: BoxConstraints(
        minWidth: MediaQuery.of(context).size.width,
        minHeight: MediaQuery.of(context).size.height - kToolbarHeight,
      ),
      child: Column(
        children: [
          widget.publishType == PublishType.video ? _videoBox() : Container(),
          widget.publishType == PublishType.file ? _fileBox() : Container(),
          widget.publishType != PublishType.moment
              ? _videoTitle()
              : Container(),
          _topLayout(context),
          widget.publishType == PublishType.moment
              ? _buildImageBox()
              : Container(),
          Container(
            margin: const EdgeInsets.all(12),
            alignment: Alignment.centerLeft,
            child: Wrap(
                spacing: 12,
                runSpacing: 6,
                children: tabModelList.asMap().entries.map((e) {
                  return Stack(
                    children: [
                      Tag(
                        e.value.name,
                        borderRadius: BorderRadius.circular(24),
                        fontSize: WcaoTheme.fsBase,
                        padding: const EdgeInsets.only(
                          top: 2,
                          bottom: 2,
                          left: 8,
                          right: 25,
                        ),
                        color: WcaoTheme.primary,
                      ),
                      Positioned(
                          right: 4,
                          bottom: 4,
                          child: InkWell(
                              onTap: () {
                                tabModelList.removeAt(e.key);
                                setState(() {
                                  tabModelList = tabModelList;
                                });
                              },
                              child: Image.asset(
                                'assets/images/icons/pubish_close_pic.png',
                                width: 14,
                                height: 14,
                              )))
                    ],
                  );
                }).toList()),
          ),
          _bottomLayout(context),
        ],
      ),
    );
  }

  _videoTitle() {
    return Container(
        margin: EdgeInsets.all(10),
        // decoration: BoxDecoration(
        //     borderRadius: BorderRadius.circular(4.0),
        //     border:
        //         Border.all(style: BorderStyle.solid, color: Colors.black26)),
        child: TextField(
          controller: _editingFileController,
          keyboardType: TextInputType.multiline,
          style: TextStyle(color: Colors.black, fontSize: 16),
          decoration: InputDecoration(
              // border: OutlineInputBorder(),
              border: InputBorder.none,
              hintText: widget.publishType == PublishType.video
                  ? '给视频取个标题吧~'
                  : '给文件取个标题吧~',
              hintStyle: TextStyle(color: Colors.grey)),
        ));
  }

  _fileBox() {
    return Container(
        padding: EdgeInsets.all(10),
        alignment: Alignment.centerLeft,
        height: 120,
        child: Stack(
          children: [
            ossFileURL != ""
                ? InkWell(
                    child: Container(
                      width: toRpx(size: 375),
                      child: Image.asset(
                        'assets/images/icons/pdf.png',
                      ),
                    ),
                  )
                : Container(
                    width: toRpx(size: 375),
                    color: Colors.grey[300],
                    alignment: Alignment.center,
                    child: Text(
                      filePercentage == 100.0
                          ? "文件上传完成"
                          : "文件上传中~,$filePercentage%",
                      style: TextStyle(
                          color: Colors.redAccent,
                          fontSize: 12,
                          fontWeight: FontWeight.w500),
                    ),
                  ),
            Positioned(
              child: InkWell(
                child: Text(widget.publishFileMgs.size,
                    style: TextStyle(
                        color: Colors.grey,
                        fontSize: 12,
                        fontWeight: FontWeight.w500)),
                onTap: _delVideoCover,
              ),
              bottom: 5,
              right: 5,
            )
          ],
        ));
  }

  _videoBox() {
    return Container(
        padding: EdgeInsets.all(10),
        child:
            Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
          Expanded(
              flex: 1,
              child: Container(
                height: 120,
                child: Stack(
                  children: [
                 InkWell(
                            onTap: (){
                              Video videoItem =   Video.fromJson({
                            "createTime": "2022-08-05 12:51:33",
                            "hasCollected": false,
                            "sourceChannel": "douyin",
                            "sourceUrl": ossFileURL,
                            "title": _editingFileController.text,
                            "updateTime": "2022-08-05 12:51:33",
                            "url": ossFileURL,
                              });
                              if(filePercentage == 100.0){
                               Get.to(VideoPage(videoItem:videoItem));
                              }
                            },
                            child:    Container(
                      color: Colors.grey[300],
                      alignment: Alignment.center,
                      child: Text(
                        filePercentage == 100.0
                            ? "视频上传完成"
                            : "视频上传中~,$filePercentage%",
                        style: TextStyle(
                            color: Colors.redAccent,
                            fontSize: 12,
                            fontWeight: FontWeight.w500),
                      ),
                    ))
                  ],
                ),
              )),
          Expanded(
              flex: 1,
              child: Container(
                height: 120,
                child: Stack(
                  children: [
                    videoCoverInfo["coverUrl"] != ""
                        ? InkWell(
                            child: Container(
                              width: toRpx(size: 375),
                              child: CgqUtils.imageCache(
                                videoCoverInfo['coverUrl'],
                                fit: BoxFit.fitWidth,
                              ),
                            ),
                          )
                        : InkWell(
                            onTap: _chooseVideoCover,
                            child: Container(
                              color: Colors.grey[100],
                              alignment: Alignment.center,
                              child: Text(
                                "上传自定义封面",
                                style: TextStyle(
                                    color: Colors.grey,
                                    fontSize: 12,
                                    fontWeight: FontWeight.w500),
                              ),
                            )),
                    videoCoverInfo["coverUrl"] != ""
                        ? Positioned(
                            child: InkWell(
                              child: Image.asset(
                                'assets/images/icons/pubish_close_pic.png',
                                width: 16,
                                height: 16,
                              ),
                              onTap: _delVideoCover,
                            ),
                            top: 5,
                            right: 5,
                          )
                        : Container()
                  ],
                ),
              ))
        ]));
  }

  _delVideoCover() {
    videoCoverInfo = {
      "coverHeight": "",
      "coverUrl": "",
      "coverWidth": "",
    };
    setState(() {
      videoCoverInfo = videoCoverInfo;
    });
  }

  _chooseVideoCover() async {
    FilePickerResult result = await FilePicker.platform.pickFiles(
      type: FileType.image,
    );
    videoCoverInfo['coverUrl'] = await UploadOss.upload(
        File(result.files.first.path),
        rootDir: "moment/image");
    Image image = Image.file(File(result.files.first.path));
    Map<String, dynamic> imageInfo;
    image.image
        .resolve(ImageConfiguration())
        .addListener(ImageStreamListener((ImageInfo info, bool _) {
      videoCoverInfo['coverWidth'] = info.image.width;
      videoCoverInfo['coverHeight'] = info.image.height;
      print(videoCoverInfo);
      setState(() {
        videoCoverInfo = videoCoverInfo;
      });
    }));
  }

  _topLayout(BuildContext context) {
    return Container(
      height: 250,
      margin: EdgeInsets.only(top: 10, bottom: 10),
      child: TextField(
        controller: _editingContentController,
        focusNode: _focusNode,
        onChanged: (value) {
          setState(() {
            momentContent = value;
          });
        },
        style: TextStyle(height: 1.5),
        cursorColor: Colors.redAccent,
        enableSuggestions: false,
        autocorrect: false,
        maxLength: 1000,
        maxLines: 50,
        minLines: 15,
        decoration: InputDecoration(
          hintText: '一起聊聊吧~',
          filled: true,
          fillColor: Colors.white,
          contentPadding:
              const EdgeInsets.symmetric(vertical: 10, horizontal: 16),
          enabledBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(20),
              borderSide: BorderSide(color: Colors.white, width: 2.0)),
          focusedBorder: OutlineInputBorder(
            borderRadius: BorderRadius.circular(20),
            borderSide: BorderSide(
              color: Colors.white,
              width: 2,
            ),
          ),
        ),
      ),
      //   style: TextStyle(color: Colors.grey[800], fontSize: 14), //文字大小、颜色
      //   decoration: InputDecoration(
      //     fillColor: Colors.white,
      //     filled: true,
      //     hintText: '一起聊聊吧~',
      //     hintStyle: TextStyle(color: Colors.grey[600]),
      //     contentPadding:
      //         const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
      //     isDense: true,
      //     border: InputBorder.none,
      //   ),
      // ),
    );
  }

  _buildImageBox() {
    double boxWidth = MediaQuery.of(context).size.width - 24;
    return Container(
      width: boxWidth,
      margin: const EdgeInsets.only(top: 8, right: 16, left: 16, bottom: 8),
      child: Wrap(
          spacing: 4,
          runSpacing: 4,
          children: this._imageFileList == null
              ? [
                  InkWell(
                    child: Container(
                      width: 96,
                      height: 96,
                      margin: EdgeInsets.only(right: 10),
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(4.0),
                          border: Border.all(
                            style: BorderStyle.solid,
                            color: Colors.black26,
                          )),
                      child: Center(
                        child: Icon(Icons.add),
                      ),
                    ),
                    onTap: _openGallery,
                  )
                ]
              : _buildImages()),
    );
  }

  List<Widget> _buildImages() {
    List<Widget> _selectimageFileList = _imageFileList
        .asMap()
        .entries
        .map((entry) => SizedBox(
              width: 96,
              height: 96,
              child: ClipRRect(
                  borderRadius: BorderRadius.circular(4),
                  child: Stack(
                    children: [
                      Container(
                        width: 96,
                        height: 96,
                        child: Image.file(
                          File(entry.value.path),
                          fit: BoxFit.cover,
                        ),
                      ),
                      Positioned(
                        child: InkWell(
                          child: Image.asset(
                            'assets/images/icons/pubish_close_pic.png',
                            width: 16,
                            height: 16,
                          ),
                          onTap: () {
                            _imageFileList.removeAt(entry.key);
                            setState(() {
                              _imageFileList = _imageFileList;
                            });
                          },
                        ),
                        top: 5,
                        right: 5,
                      )
                    ],
                  )),
            ))
        .toList();
    Widget inkWell = SizedBox(
        width: 108,
        height: 96,
        child: InkWell(
          child: Container(
            margin: EdgeInsets.only(right: 10),
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(4.0),
                border: Border.all(
                  style: BorderStyle.solid,
                  color: Colors.black26,
                )),
            child: Center(
              child: Icon(
                Icons.add,
                size: 56,
                color: Colors.grey,
              ),
            ),
          ),
          onTap: _selectImages,
        ));
    if (_imageFileList.length < 9) {
      _selectimageFileList.add(inkWell);
    }

    return _selectimageFileList;
  }

  //选择相册照片
  void _openGallery() async {
    final List<XFile> pickedFileList = await _picker.pickMultiImage();
    // List<XFile> newList=  new List.from(_imageFileList)..addAll(pickedFileList);

    setState(() {
      _imageFileList = pickedFileList;
    });
  }

  _selectImages() async {
    List<XFile> result = await _picker.pickMultiImage();
    if (result != null) {
      List<File> files = result.map((val) => File(val.path)).toList();
      files.forEach((element) {
        Image image = Image.file(element);
        SelectImageInfo imageInfo = SelectImageInfo();
        image.image
            .resolve(ImageConfiguration())
            .addListener(ImageStreamListener((ImageInfo info, bool _) {
          print(info.image.width);
          imageInfo.width = info.image.width;
          imageInfo.height = info.image.height;
          imageInfo.path = element.path;
          _imageFileList.add(imageInfo);
          setState(() {
            _imageFileList = _imageFileList;
          });
        }));
      });
      setState(() {
        _imageFileList = _imageFileList;
      });
    } else {
      // User canceled the picker
    }
  }

  //展示好友
  void showBottomFriendList() {
    setState(() {
      _focusNode.unfocus();
    });
    showModalBottomSheet(
        backgroundColor: Colors.white,
        context: context,
        isScrollControlled: true, //可滚动 解除showModalBottomSheet最大显示屏幕一半的限制
        shape: RoundedRectangleBorder(
          borderRadius: const BorderRadius.only(
            topLeft: Radius.circular(10),
            topRight: Radius.circular(10),
          ),
        ),
        builder: (context) {
          return Container(
              constraints: BoxConstraints(
                  minHeight: MediaQuery.of(context).size.height -
                      kToolbarHeight, //设置最小高度（必要） //设置最小高度（必要）
                  maxHeight: MediaQuery.of(context).size.height
                  // -
                  //     kToolbarHeight, //设置最大高度（必要）
                  ),
              child: FriendListSelectPublishIndexPage());
        });
  }

  void showBottomTabList() {
    setState(() {
      _focusNode.unfocus();
    });
    showModalBottomSheet(
        backgroundColor: Colors.white,
        context: context,
        isScrollControlled: true, //可滚动 解除showModalBottomSheet最大显示屏幕一半的限制
        shape: RoundedRectangleBorder(
          borderRadius: const BorderRadius.only(
            topLeft: Radius.circular(10),
            topRight: Radius.circular(10),
          ),
        ),
        builder: (context) {
          return Container(
              constraints: BoxConstraints(
                  minHeight: MediaQuery.of(context).size.height -
                      kToolbarHeight, //设置最小高度（必要）
                  maxHeight: MediaQuery.of(context).size.height
                  // -
                  //     kToolbarHeight, //设置最大高度（必要）
                  ),
              child: TabListPublish());
        });
  }

  //展示主题
  void showBottomTopic() {
    setState(() {
      _focusNode.unfocus();
    });
    showModalBottomSheet(
        backgroundColor: Colors.white,
        context: context,
        isScrollControlled: true, //可滚动 解除showModalBottomSheet最大显示屏幕一半的限制
        shape: RoundedRectangleBorder(
          borderRadius: const BorderRadius.only(
            topLeft: Radius.circular(10),
            topRight: Radius.circular(10),
          ),
        ),
        builder: (context) {
          return Container(
              // margin: EdgeInsets.only(top: kToolbarHeight),
              constraints: BoxConstraints(
                  minHeight: MediaQuery.of(context).size.height -
                      kToolbarHeight, //设置最小高度（必要）
                  maxHeight: MediaQuery.of(context).size.height
                  //  -
                  //     kToolbarHeight, //设置最大高度（必要）
                  ),
              child: TopicListPublishIndexPage());
        });
  }

  _bottomLayout(BuildContext context) {
    return Container(
        padding: EdgeInsets.all(10),
        margin: EdgeInsets.only(top: 20),
        decoration: BoxDecoration(
          border: Border.all(color: Colors.grey[300], width: 0.5),
        ),
        child:
            Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
          Row(children: [
            Container(
              width: 50,
              height: 30,
              alignment: Alignment.center,
              child: GestureDetector(
                onTap: showBottomFriendList,
                child: Image.asset(
                  'assets/images/icons/publish_at.png',
                  width: 24,
                  height: 24,
                ),
              ),
            ),
            Container(
              width: 50,
              height: 30,
              alignment: Alignment.center,
              child: GestureDetector(
                onTap: showBottomTopic,
                child: Image.asset(
                  'assets/images/icons/publish_topic.png',
                  width: 24,
                  height: 24,
                ),
              ),
            ),
            Container(
              width: 50,
              height: 30,
              alignment: Alignment.center,
              child: GestureDetector(
                onTap: showBottomTabList,
                child: Image.asset(
                  'assets/images/icons/publish_tag.png',
                  width: 24,
                  height: 24,
                ),
              ),
            )
          ]),
          Row(children: [
            // Container(
            //   width: 50,
            //   height: 30,
            //   alignment: Alignment.center,
            //   child: Text(
            //     momentContent.length.toString(),
            //     style: TextStyle(
            //         color: Colors.grey,
            //         fontSize: 12,
            //         fontWeight: FontWeight.w500),
            //   ),
            // ),
            // ClipRRect(
            //     borderRadius: BorderRadius.circular(20),
            //     child: Container(
            //       color: Colors.redAccent,
            //       width: 60,
            //       height: 30,
            //       alignment: Alignment.center,
            //       child: GestureDetector(
            //         onTap: _publish,
            //         child: Text(
            //           '发布',
            //           style: TextStyle(
            //               color: Colors.white,
            //               fontSize: 12,
            //               fontWeight: FontWeight.w500),
            //         ),
            //       ),
            //     )),
          ])
        ]));
  }

  _publish() async {
    EasyLoading.show(status: '发布中...');
    try {
      setState(() {
        disabledPublish = false;
      });
      Map<String, dynamic> param = {
        "momentType": momentType,
        "textContent": momentContent,
      };
      if (tabModelList.length > 0) {
        List<int> tagIdList = [];
        tabModelList.forEach((element) {
          tagIdList.add(element.id);
        });
        param["tagIdList"] = tagIdList;
      }
      if (_imageFileList.length > 0) {
        this.momentType = 'IMAGE';
      }
      if (this.momentType == 'MOMENT') {
        param["momentType"] = 'TEXT';
      }
      if (this.momentType == 'IMAGE') {
        param["momentType"] = 'IMAGE';
        param['imageList'] = [];
        for (int i = 0; i < _imageFileList.length; i++) {
          Map<String, dynamic> uploadImageInfo = {};
          uploadImageInfo['url'] = await UploadOss.upload(
              File(_imageFileList[i].path),
              rootDir: "moment/image");
          uploadImageInfo['width'] = _imageFileList[i].width;
          uploadImageInfo['height'] = _imageFileList[i].height;
          param['imageList'].add(uploadImageInfo);
        }
      }
      if (this.momentType == 'VIDEO') {
        param['video'] = {
          "height": videoPlayerController.value.size.height,
          "width": videoPlayerController.value.size.width,
          "size": widget.publishFileMgs.size,
          "title": _editingFileController.text,
          "url": ossFileURL,
          "sourceUrl": widget.videoSourceUrl,
          "sourceChannel": "douyin",
          "coverHeight": videoCoverInfo['coverHeight'],
          "coverUrl": videoCoverInfo['coverUrl'],
          "coverWidth": videoCoverInfo['coverWidth'],
        };
      }
      if (this.momentType == 'FILE') {
        param['file'] = {
          "size": widget.publishFileMgs.size,
          "title": _editingFileController.text,
          "url": ossFileURL
        };
      }
      if (param["momentType"] == 'TEXT' && momentContent == "") {
        ToastUtils.showToast("你没填写内容哦！");
        EasyLoading.dismiss(animation: true);
        Future.delayed(Duration(milliseconds: 1000), () {
          setState(() {
            disabledPublish = true;
          });
        });
        return;
      }
      await PublishService.publishMoment(param)
          .then((value) => {ToastUtils.showToast("发布成功!"), Get.back()})
          .catchError((error) => {
                ToastUtils.showToast(error['retdesc']),
                setState(() {
                  disabledPublish = true;
                })
              });
      EasyLoading.dismiss(animation: true);
    } catch (e) {
      setState(() {
        disabledPublish = true;
      });
      EasyLoading.showError('发布失败');
      EasyLoading.dismiss(animation: true);
    }
  }
}
